package cn.com.lgyw.jdbc.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.com.lgyw.jdbc.bean.ConnectionBean;
import cn.com.lgyw.jdbc.connection.ConnectionPool;
import cn.com.lgyw.jdbc.transaction.TransactionUtil;


/**
 * jdbc 抽象模版类,执行完成后关闭连接
 * 
 * @author guojian
 *
 */
public abstract class AbstractorJdbcExecute {

	private static final Log log = LogFactory.getLog(AbstractorJdbcExecute.class);

	static Object execute(JdbcExecute e, ConnectionBean con, String sql, String typeName, List<?> fields) {
		ResultSet result = null;
		Statement statement = null;
		Object[] resultObject = null;
		Connection conn = con.getCon();
		if (conn == null) {
			return null;
		}
		// 判断是否开启了事务
		boolean isBeginTransaction = TransactionUtil.transactionState.get() == null ? false : true;
		if (isBeginTransaction) {
			try {
				conn.setAutoCommit(false);
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			List<ConnectionBean> conBeans = TransactionUtil.connectionBeanThread.get();
			if (conBeans == null) {
				conBeans = new ArrayList<ConnectionBean>();
				conBeans.add(con);
				TransactionUtil.connectionBeanThread.set(conBeans);
			} else {
				if (!conBeans.contains(con)) {
					conBeans.add(con);
				}
			}
		}
		try {
			resultObject = e.execute(conn, sql, fields);
			statement = resultObject[0] == null ? null : (Statement) resultObject[0];
			if (isBeginTransaction) {
				List<Statement> statements = TransactionUtil.statementThread.get();
				if (statements == null) {
					statements = new ArrayList<Statement>();
					statements.add(statement);
					TransactionUtil.statementThread.set(statements);
				} else {
					statements.add(statement);
				}
			}
			result = resultObject[1] == null ? null : (ResultSet) resultObject[1];
		} catch (Exception e1) {
			// 设置异常状态,回滚的标示
			TransactionUtil.exceptionState.set(true);
			//clearAllConnection(typeName);
			log.error(e1);
		} finally {
			if (!isBeginTransaction) {
				closeConnection(conn, typeName, result, statement);
			}
		}
		return resultObject == null ? resultObject : resultObject[2];
	}

	static void clearAllConnection(String typeName) {
		ConnectionPool.clearAllConnection(typeName);
	}

	static void closeConnection(Connection con, String typeName, ResultSet result, Statement statement) {
		ConnectionPool.closeConnection(con, typeName, result, statement);
	}

}
